<template>
  <div class="tableListBox">
    <div class="blueTitleView">
      <p class="titleview">收样台账</p>
    </div>
    <div class="iuapContent">
      <div class="content-form">
        <IuapSearch :fromData="fromData" @searchFn="(e) => {
          this.searchFn(e);
        }
          " @reset="(e) => {
    this.reset(e);
  }
    ">
        </IuapSearch>
      </div>
      <div class="content-form__operation">
        <vxe-button status="primary" size="small" @click="add">新增收样单</vxe-button>
        <vxe-button status="primary" size="small" @click="copy">复制</vxe-button>
      </div>
      <div class="tableList">
        <div class="onlyTable">
          <vxe-grid class="table-normal" ref="table" resizable show-overflow row-key keep-source border="inner"
            :data="tableData" :columns="columns"
            :row-class-name="({ row, rowIndex, $rowIndex }) => { return row.isDiscarded ? 'isDiscarded' : ''; }"
            max-height="100%">

            <template #contractStatus="{ row }">
              <span>{{ row.contractStatus | getContractStatus }}</span>
            </template>
            <template #contractSigningDate="{ row }">
              <span>{{ row.contractSigningDate | parseTime('{y}-{m}-{d}') }}</span>
            </template>

            <template #operation="{ row }">
              <vxe-button size="mini" status="info" @click="collapse(row)">{{ collapsed ? '展开' : '收起' }}</vxe-button>
              <!-- <vxe-button size="mini" status="info" @click="!row.isDiscarded && check(row)">详情</vxe-button> -->
              <vxe-button size="mini" status="info" @click="!row.isDiscarded && settlement(row)">生成结算单</vxe-button>
              <vxe-button size="mini" status="info" @click="!row.isDiscarded && sendReport(row)">报告发送登记</vxe-button>
              <vxe-button size="mini" status="info" @click="!row.isDiscarded && inspectionReport(row)">检测报告上传</vxe-button>
              <vxe-button size="mini" status="info" @click="!row.isDiscarded && hoursRegister(row)">工时登记</vxe-button>
              <!-- <vxe-button size="mini" status="info" @click="!row.isDiscarded && settleRegister(row)">结算单上传</vxe-button> -->
            </template>
          </vxe-grid>
        </div>
        <vxe-pager background :current-page.sync="form.page" :page-size.sync="form.size" :total="total"
          :layouts="['Total', 'Sizes', 'PrevPage', 'JumpNumber', 'NextPage']" @page-change="pager">
        </vxe-pager>
      </div>
    </div>
    <AddSample ref="sample" @reload="getList" />
    <SendReport ref="sendReport" />
    <InspectionReport ref="inspectionReport" />
    <HoursRegister ref="hoursRegister" />
    <SettleRegister ref="settleRegister" />
  </div>
</template>
<script>
import util from '../../util/util';
import IuapSearch from '/@/components/Iuap/IuapSearch.vue';
import AddSample from './dialog/add.vue';
import SendReport from './dialog/sendReport.vue';
import InspectionReport from './dialog/inspectionReport.vue';
import HoursRegister from './dialog/hoursRegister.vue';
import SettleRegister from './dialog/settleRegister.vue';

import VXETable from 'vxe-table';
import * as ExcelJS from 'exceljs';
export default {
  components: { IuapSearch, AddSample, SendReport, InspectionReport, HoursRegister, SettleRegister },
  data() {
    return {
      collapsed: true,
      form: {
        page: 1,
        size: 10,
      },
      formData: {
        batchNumber: '',
        contractId: null,
        engineeringPart: '',
        entrustName: '',
        entrustNumber: '',
        entrustType: '',
        entrustDate: '',
        isExternal: false,
        isSupplement: false,
        manufacturer: '',
        pricingType: '',
        reportNumber: '',
        remarks: '',
        sampleOrderDetailCmdList: [],
        specModel: '',
      },
      columns: [
        { type: 'radio', width: 60, title: '', align: 'center', },
        {
          field: 'reportNumber', title: '报告编号', width: 180, editRender: {}, slots: {
            default: ({ row }) => {
              return [<span style="cursor: pointer;color:blue;" onClick={() => this.check(row)}>{row.reportNumber}</span>,];
            },
          },
        },
        {
          field: 'projectName', title: '工程名称', width: 130, editRender: {},
          slots: {
            default: ({ row }) => {
              return [<span style="cursor: pointer;color:blue" onClick={() => this.settlement(row)}>{row.projectName}</span>,];
            },
          },
        },
        { field: 'entrustNumber', title: '委托编号', width: 130, editRender: {}, },
        { field: 'entrustDate', title: '委托日期', width: 130, editRender: {}, formatter({ cellValue }) { return util.parseTime(cellValue, '{y}-{m}-{d}'); }, },
        { field: 'itemName', title: '检测项目', width: 130, editRender: {}, },
        // {field: 'contractSigningDate',title: '单位',width: 80,editRender: {},slots: { default: 'contractSigningDate' },},
        { field: 'detailTotalAmount', title: '合价', width: 130, editRender: {}, },
        { field: 'submitReportTime', title: '出报告日期', width: 130, editRender: {}, formatter({ cellValue }) { return util.parseTime(cellValue, '{y}-{m}-{d}'); }, },
        { field: 'sendReportTime', title: '发报告日期', width: 130, editRender: {}, formatter({ cellValue }) { return util.parseTime(cellValue, '{y}-{m}-{d}'); }, },
        {
          field: 'isTimesheetCompleted', width: 180, title: '是否完成工时登记', editRender: {},
          slots: {
            default: ({ row }, h) => {
              const isCompleted = row.isTimesheetCompleted;
              return h('span', {
                class: {
                  'green-background': isCompleted,
                  'red-background': !isCompleted,
                },
              }, isCompleted ? '是' : '否');
            },
          },

        },
        {
          field: 'isSettled', title: '是否办理结算', width: 180, editRender: {},
          slots: {
            default: ({ row }, h) => {
              const isSettled = row.isSettled;
              return h('span', {
                class: {
                  'green-background': isSettled,
                  'red-background': !isSettled,
                },
              }, isSettled ? '是' : '否');
            },
          },
        },
        { field: 'remarks', title: '备注', width: 180, editRender: {}, },
        { field: 'operation', title: '操作', width: 180, headerAlign: 'left', fixed: 'right', slots: { default: 'operation' }, },
      ],
      tableData: [],
      total: 0,
      fromData: [
        {
          name: '工程名称',
          key: 'projectName',
          type: 'input',
          value: '',
        },
        {
          name: '报告编号',
          key: 'reportNumber',
          type: 'input',
          value: '',
        },
        {
          name: '委托日期',
          key: 'entrustDate',
          type: 'date',
          value: '',
        },
        {
          name: '检测项目',
          key: 'itemName',
          type: 'input',
          value: '',
        },
        {
          name: '出报告日期',
          key: 'submitReportTime',
          type: 'date',
          value: '',
        },
        {
          name: '发报告日期',
          key: 'sendReportTime',
          type: 'date',
          value: '',
        },
        {
          name: '是否办理结算',
          key: 'isSettled',
          type: 'option',
          value: '',
          options: [
            {
              label: '是',
              value: true,
            },

            {
              label: '否',
              value: false,
            },
          ],
        },
        {
          name: '是否结算完成',
          key: 'isSettleCompleted',
          type: 'option',
          value: '',
          options: [
            {
              label: '是',
              value: true,
            },

            {
              label: '否',
              value: false,
            },
          ],
        },
      ],
    };
  },
  filters: {
    getContractStatus(val) {
      return val === 'COMPLETED' ? '完成' : '未完成';
    },
  },
  created() {
    this.getList(); //记得打开
  },
  methods: {
    async getList() {
      await this.$api.getSampleOrderPage(this.form).then((res) => {
        try {
          const { list, total } = res.data;
          this.tableData = list;
          // console.log(this.tableData,123456);
          this.total = total;
        } catch { }
      });
    },
    pager({ currentPage, pageSize }) {
      this.form.page = currentPage;
      this.form.size = pageSize;
      this.getList();
    },
    search() {
      this.form.page = 1;
      this.getList();
    },
    searchFn(e) {
      this.fromData.forEach((item) => {
        this.form[item.key] = item.value;
      });
      this.form.page = 1;
      this.getList();
    },
    reset() {
      this.form = {
        page: 1,
        size: 10,
      };
      this.getList();
    },
    add() {
      this.$refs.sample.dialogVisible = true;
    },
    check(row) {
      const { id } = row;
      this.$router.push({ path: '/ledgerManage/check', query: { sampleId: id } });

    },
    settlement(row) {
      const { contractId, projectName, companyName, contractStatus } = row;
      this.$router.push({
        path: '/ledgerManage/addSettlement',
        query: { contractId, projectName, companyName, contractStatus },
      });
    },
    sendReport(row) {
      const { id: sampleId, projectName, reportNumber, itemName } = row;
      this.$refs.sendReport.form = { sampleId, projectName, reportNumber, itemName };
      this.$api.getReportSend({ sampleId }).then((res) => {
        this.$refs.sendReport.reportForm.fileList = res.data.fileList || []
      })
      this.$refs.sendReport.dialogVisible = true;
    },
    inspectionReport(row) {
      const { id: sampleId, projectName, reportNumber, itemName } = row;
      this.$refs.inspectionReport.form = { sampleId, projectName, reportNumber, itemName };
      this.$api.getReportSubmit({ sampleId }).then((res) => {
        this.$refs.inspectionReport.reportForm.fileList = res.data.fileList || []
      })
      this.$refs.inspectionReport.dialogVisible = true;
    },
    hoursRegister(row) {
      const { id: sampleId, projectName, reportNumber, itemName, detailTotalWorkingHours } = row;
      this.$refs.hoursRegister.form = {
        sampleId,
        projectName,
        reportNumber,
        itemName,
        totalWorkingHours: detailTotalWorkingHours,
      };
      this.$api.getTimesheetBySampleId({ sampleId }).then((res) => {
        this.$refs.hoursRegister.tableData = res.data;
      });
      this.$refs.hoursRegister.dialogVisible = true;
    },
    settleRegister(row) {
      const { id: sampleId, projectName, reportNumber, itemName } = row;
      this.$refs.settleRegister.form = { sampleId, projectName, reportNumber, itemName };
      this.$refs.settleRegister.dialogVisible = true;
    },
    async copy() {
      const $table = this.$refs.table;
      const selectRecord = $table.getRadioRecord();
      if (selectRecord) {
        const type = await VXETable.modal.confirm('您确定要复制所选数据?');
        // 先获取详情
        const formData = await this.getSampleOrder(selectRecord);
        const { reportNumber, entrustNumber, ...rest } = formData;
        if (type === 'confirm') {
          this.addSampleOrder(rest);
        }
      } else {
        VXETable.modal.message({ status: 'warning', content: '未选中数据！' });
        return;
      }
    },
    async getSampleOrder(row) {
      const formData = { ...this.formData };
      return await this.$api.getSampleOrder({ sampleId: row.id }).then((res) => {
        const data = res.data;
        Object.keys(formData).forEach((key) => {
          formData[key] = data[key];
        });
        formData.sampleOrderDetailCmdList = data.sampleOrderDetailList.map((item) => {
          return {
            paramId: item.paramId,
            detectionStdId: item.detectionStdId,
          };
        });
        formData.infoId = data.contractInfo.chargeStdId;
        return formData;
      });
    },
    async addSampleOrder(formData) {
      await this.$api.addSampleOrder({ ...formData }).then((res) => {
        VXETable.modal.message({
          content: '新增成功',
          status: 'success',
        });
        this.getList();
      });
    },
    checkFileList(row) {
      const item = row.contractFile;
      const a = document.createElement('a');
      a.target = '_blank';
      a.href = item.fileUrl;
      a.click();
    },
    // 控制右侧按钮展开与收起
    collapse(row) {
      // collapsed: true,  初始collapsed
      this.columns.forEach((item) => {
        // 对应这个的
        if (item.field === 'operation') {
          if (this.collapsed) {
            item.width = 500;
            this.collapsed = false;
          } else {
            item.width = 130;
            this.collapsed = true;
          }
        }
      });
      this.$refs.table.loadColumn(this.columns);
    },
  },
};
</script>
<style lang="scss" scoped>
.vxe-button.type--button.theme--primary {
  height: 28px;
  font-size: 12px;
  background-color: rgb(31, 143, 255) !important;
  border-color: rgb(31, 143, 255) !important;
}

.vxe-button.type--button.size--mini {
  height: 21px;
  line-height: 21px;
  font-size: 12px;
}

.vxe-form--item-title-label {
  font-size: 13px;
}

.tableListBox {
  height: 100vh;

  .tableList {
    ::v-deep {
      .vxe-form.outForm {
        .vxe-form--item-content {
          width: 280px;
        }

        .vxe-form--item {
          width: 28%;
        }

        .last-item {
          width: 16%;
          text-align: right;
        }
      }

      .vxe-table--body-wrapper {
        overflow-y: auto !important;
      }

      .table-normal .vxe-header--row {
        height: 30px;
      }

      .vxe-table--render-default .vxe-header--column:not(.col--ellipsis) {
        padding: 0 !important;
        font-size: 13px;
      }

      .vxe-table--render-default .vxe-body--column.col--ellipsis {
        height: 35px;
        font-size: 13px;
      }

      .vxe-button.type--text.theme--info {
        color: #06f;
        cursor: pointer;
        line-height: 1;
      }

      .vxe-button.type--button.size--mini.theme--info:not(.is--disabled) {
        background-color: #505766 !important;
        border-color: #505766 !important;
        // height: 20px;
        border-radius: 2px;
      }

      .vxe-button.type--button.size--small.theme--info:not(.is--disabled) {
        background-color: #505766 !important;
        border-color: #505766 !important;
        // height: 26px;
        border-radius: 2px;
      }

      .vxe-pager--wrapper button.is--active {
        background-color: #adb4bc !important;
        border-color: #adb4bc !important;
        box-shadow: none;
      }

      // 作废行的样式
      .isDiscarded {
        opacity: 0.5;

        .vxe-button {
          cursor: no-drop;
        }
      }

      // “是否完成工时登记”和“是否办理结算”做底色区分，“是”为绿色，否为红色
      .green-background {
        font-weight: 600;
        color: green;
      }

      .red-background {
        font-weight: 600;
        color: red;
      }
    }
  }
}
</style>
